from os.path import exists

from django.shortcuts import render,redirect

from app01 import models
from django import forms
from django.core.exceptions import ValidationError
from app01.utils.bootstrap import BootStrapModelForm
from app01.utils.pagination import Pagination
from app01.utils.encrypt import md5



def admin_list(request):
    """ 管理员列表 """

    # # 检查用户是否已登录，已登录，继续走下去，未登录，跳转回登录页面。
    # # 用户发来请求，获取Cookie随机字符串，拿着随机字符串看看session中有没有。
    # info = request.session.get('info')
    # # print(info)
    # # {'id': 1, 'name': 'No01'}
    # # 搜索
    # if not info:
    #     return redirect('/login/')

    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["username__contains"] = search_data

    # 根据搜索条件去数据库获取
    queryset = models.Admin.objects.filter(**data_dict)

    # 分页
    page_object = Pagination(request,queryset)
    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html(),
        # 搜索框保留搜索记录值
        "search_data": search_data,
    }
    return render(request,'admin_list.html',context)

class AdminModelForm(BootStrapModelForm):
    # 再次输入密码框
    confirm_password = forms.CharField(
        label="确认密码",
        # 确认密码输入隐藏模式,加入render_value=True参数，表示当两次输入的密码不一致时，密码不要清空，默认是清空
        widget=forms.PasswordInput(render_value=True),
    )
    class Meta:
        model = models.Admin
        fields = ["username","password","confirm_password"]
        widgets = {
            # 密码输入隐藏模式
            "password": forms.PasswordInput(render_value=True),
        }

    # MD5密码加密
    def clean_password(self):
        pwd = self.cleaned_data['password']
        return md5(pwd)

    # hook钩子校验，注意clean_后面接的是要处理的对象，函数名不能乱写
    def clean_confirm_password(self):
        # print(self.cleaned_data)
        pwd = self.cleaned_data.get("password")
        confirm = md5(self.cleaned_data.get("confirm_password"))
        # 这里得到是加密后的密文 bed5aef27cd7f17e98ea92b8cda340af,c7f980937a71596efb79385747965ba8
        # print(f"{pwd},{confirm}")
        if confirm != pwd:
            raise ValidationError("两次输入密码不一致")
        # 这个return返回的值，放入cleaned_data，并会被form.save()保存到数据库
        return confirm

class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = models.Admin
        fields = ["username"]

class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        # 确认密码输入隐藏模式,加入render_value=True参数，表示当两次输入的密码不一致时，密码不要清空，默认是清空
        widget=forms.PasswordInput(render_value=True),
    )
    class Meta:
        model = models.Admin
        fields = ["password","confirm_password"]
        widgets = {
            # 密码输入隐藏模式
            "password": forms.PasswordInput(render_value=True),
        }

    def clean_password(self):
        pwd = self.cleaned_data['password']
        md5_pwd = md5(pwd)
        # 去数据库校验当前密码和新输入的密码是否一致
        exists = models.Admin.objects.filter(id=self.instance.pk,password=md5_pwd).exists()
        if exists:
            raise ValidationError("新密码不能跟之前的一致")

        return md5_pwd

    # hook钩子校验，注意clean_后面接的是要处理的对象，函数名不能乱写
    def clean_confirm_password(self):
        # print(self.cleaned_data)
        pwd = self.cleaned_data.get("password")
        confirm = md5(self.cleaned_data.get("confirm_password"))
        # 这里得到是加密后的密文 bed5aef27cd7f17e98ea92b8cda340af,c7f980937a71596efb79385747965ba8
        # print(f"{pwd},{confirm}")
        if confirm != pwd:
            raise ValidationError("新密码不能跟之前的一致")
        # 这个return返回的值，放入cleaned_data，并会被form.save()保存到数据库
        return confirm


def admin_add(request):
    """ 添加管理员账号 """
    title = "新建管理员"

    if request.method == "GET":
        form = AdminModelForm()
        return render(request,"change.html",{"form": form,"title": title})

    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        # {'username': 'root01', 'password': '321', 'confirm_password': '654'}
        form.save()
        return redirect("/admin/list/")
    return render(request,"change.html",{"form": form,"title": title})

def admin_edit(request,nid):
    """ 编辑管理员 """
    # 对象/None
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return render(request,'error.html',{"msg": "数据不存在"})

    title = "编辑管理员"

    if request.method == "GET":
        # 加上instance=row_object参数，显示默认值
        form = AdminEditModelForm(instance=row_object)
        return render(request,"change.html",{"form": form,"title": title})

    form = AdminEditModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/admin/list/")
    return render(request,"change.html",{"form": form,"title": title})

def admin_reset(request,nid):
    """重置密码"""
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return redirect('/admin/list/')
    # 占位符"重置密码 - {}"
    title = "重置密码 - {}".format(row_object.username)
    if request.method == "GET":
        form = AdminResetModelForm()
        return render(request, "change.html", {"form": form, "title": title})

    form = AdminResetModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request,"change.html",{"form": form,"title": title})

def admin_delete(request,nid):
    models.Admin.objects.filter(id=nid).delete()
    return redirect("/admin/list/")
